<template>
  <div class="container">
    <!-- 顶部区域 -->
    <div class="topDiv"></div>
    <!-- 页面上方 -->
    <div class="loginDiv">
      <!-- 蝶飞人才图片 -->
      <div class="loginL">
        <img src="@/assets/images/LOGO.png" alt="LOGO" />
        <img src="@/assets/images/view_logo40.png" alt="View Logo" />
      </div>
      <div class="loginAddress">
        <div class="add1"></div>
      </div>
      <!-- 搜索栏 -->
      <div class="loginC">
        <input type="text" placeholder="请填写关键词或选择职位..." />
        <button id="search_btn" @click="search"></button>
      </div>
      <!-- 人才网图片 -->
      <div class="loginR">
        <img src="@/assets/images/spirit_40.png" alt="Spirit Logo" />
      </div>
    </div>

    <!-- 菜单区域 -->
    <div class="menuDiv">
      <a href="index.html" class="onnav">首页</a>
      <a @click="personalIndex">个人中心</a>
      <a @click="personalSelect">我的职位</a>
    </div>

    <!-- 主体内容 -->
    <div class="BodyMain">
      <div class="mainTop">
        <!-- 分类列表 -->
        <div class="mainTopL">
          <ul>
            <li
              v-for="(value, index) in industrydata"
              :key="index"
              @click="industry(value.id)"
            >
              <div class="items">
                <div class="itemOne">
                  <span :class="'itme' + (index + 1)"
                    ><b></b>{{ value.industryName }}</span
                  >
                </div>
              </div>
            </li>
          </ul>
        </div>
        <div class="mainTopR">
          <!-- 轮播图 -->
          <div class="ads" id="carousel">
            <!-- 左边按钮 -->
            <div class="floatL" id="carouselLeft" @click="changeCarousel"></div>
            <!-- 中间图片 -->
            <div class="adBox0">
              <ul style="margin-left: 0px; overflow: hidden">
                <li>
                  <div
                    style="
                      background-size: cover;
                      background-repeat: no-repeat;
                      background-position: center;
                    "
                  >
                    <img :src="carouselImage" />
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <!-- 登录模块 -->
          <div id="loginUser" v-if="!loginStatus">
            <div class="login">
              <div class="logintop">
                <div class="loginC select">
                  <span>个人登录</span>
                </div>
              </div>
              <div class="loginmain">
                <div class="ContentA">
                  <el-form
                    :model="user"
                    :rules="rules"
                    @keyup.enter="userLogin"
                  >
                    <el-form-item label="账号" prop="username">
                      <el-input
                        type="text"
                        v-model="user.username"
                        placeholder="请输入账号"
                      />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                      <el-input
                        type="password"
                        v-model="user.password"
                        placeholder="请输入密码"
                      />
                    </el-form-item>
                  </el-form>

                  <div class="txtbtn">
                    <div style="float: left">
                      <br />
                      <div class="clear"></div>
                      <router-link to="/forgetPassword" class="forgot-password"
                        >忘记密码？</router-link
                      >
                    </div>
                    <input
                      type="button"
                      class="lobtn"
                      value="登  录"
                      @click="userLogin"
                      :disabled="isDisabled"
                    />
                  </div>
                  <div class="zcbox">
                    <div class="zc2">
                      <a class="a1" @click="resumeWrite">一分钟填写简历</a>
                      <router-link to="/register" class="a2">注册</router-link>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div id="loginUser" v-if="loginStatus">
            <div class="login">
              <div class="logintop">
                <div class="loginC select">
                  <span>登录中</span>
                </div>
              </div>
              <div class="loginmain">
                <div class="ContentA">
                  <div class="welcome-message">
                    <p>欢迎回来，{{ store.state.user.nickname }}！</p>
                    <br />
                    <p class="greeting-blessing">成就未来，与你共成长！</p>
                    <div class="greeting-blessing">
                      <p>祝您找到理想工作，开启职业新篇章！</p>
                    </div>
                  </div>
                  <br /><br />
                  <div class="loginbbtn">
                    <el-button-group>
                      <el-button
                        color="#ff9224"
                        style="color: #ffffff"
                        @click="resumeWrite"
                        >一分钟填写简历</el-button
                      >
                      <el-button color="#01b468" @click="logout"
                        >安全退出</el-button
                      >
                    </el-button-group>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 高薪职位 -->
      <div class="mainCon2">
        <!-- 首行 -->
        <div class="commontitdiv">
          <div class="title">高薪职位</div>
          <span>高薪就这么任性！</span>
        </div>
        <!-- 高薪职位列表 -->
        <div class="highMoney">
          <div
            class="divBox"
            v-for="(job, index) in detaildata"
            :key="index"
            @click="jobinfo(job.id)"
          >
            <a href="#">
              <img src="@/assets/images/18.gif" width="84" alt="Job 1" />
            </a>
            <p class="tit">
              <a href="#">{{ job.jobName }}</a>
            </p>
            <p class="sub">
              <a href="#">{{ job.enterpriseName }}</a>
            </p>
            <p class="num">
              <span>{{ job.minSalary }}K-{{ job.maxSalary }}K</span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div style="display: flex; justify-content: center">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 底部区域 -->
    <div class="footerLine"></div>
    <div class="footer">
      <div class="footerdown"></div>
    </div>
  </div>
</template>

<script setup>
import router from "@/router";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { highjobquery } from "@/api/high.js";
import { getEnterpriseInfo } from "@/api/enterprise.js";
import { fetchIndustryList } from "@/api/industryall.js";
import { jobByIndustryId } from "@/api/jobByIndustryId.js";
//定义分页相关的数据
const total = ref(0); // 总记录数
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的条目数

//定义job数据模型
const detaildata = ref([]);
//定义industry数据模型
const industrydata = ref([]);
//调用industryall接口获取数据

const getindustry = async () => {
  try {
    const result = await fetchIndustryList();
    industrydata.value = result.data.data;
    console.log("行业数据:", result.data.data);
  } catch (error) {
    console.error("请求失败");
  }
};

//点击行业名显示高薪工作
const industry = async (id) => {
  // 重置分页参数
  currentPage.value = 1;
  pageSize.value = 10; //

  const result = await jobByIndustryId(id, currentPage.value, pageSize.value);
  //console.log("job数据:", result.data.data.items);
  //alert(id);
  total.value = result.data.data.total;
  const jobsWithEnterprise = await Promise.all(
    result.data.data.items.map(async (job) => {
      const enterpriseResponse = await getEnterpriseInfo(job.enterpriseId);
      //console.log('哈哈:', enterpriseResponse);
      //console.log('哈哈哈哈哈:', enterpriseResponse.data.data.items[0].enterpriseName);
      return {
        ...job,
        enterpriseName: enterpriseResponse.data.data.items[0].enterpriseName,
      };
    })
  );

  detaildata.value = jobsWithEnterprise;
};

/***/

const detail = async () => {
  try {
    let result = await highjobquery(currentPage.value, pageSize.value);
    console.log("请求结果:", result.data); // 打印请求结果
    //遍历职位数据,获取企业详情信息
    total.value = result.data.data.total;

    const jobsWithEnterprise = await Promise.all(
      result.data.data.items.map(async (job) => {
        const enterpriseResponse = await getEnterpriseInfo(job.enterpriseId);
        //console.log('哈哈:', enterpriseResponse);
        //console.log('哈哈哈哈哈:', enterpriseResponse.data.data.items[0].enterpriseName);
        return {
          ...job,
          enterpriseName: enterpriseResponse.data.data.items[0].enterpriseName,
        };
      })
    );

    detaildata.value = jobsWithEnterprise; // 使用更新后的 jobsWithEnterprise 数组替换原始数据
    //console.log('总数据:',jobsWithEnterprise);
    //console.log('职位数据:', result.data.data.items);
    //console.log('企业信息:', enterpriseResponse.data.data);

    //detaildata.value = result.data.data.items
  } catch (error) {
    console.error("请求失败");
    console.error("请求失败:", error); // 打印错误信息
  }
};
const handlePageChange = async (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  await detail(); // 重新请求数据
};

// 页面加载时自动调用
onMounted(() => {
  detail();
  getindustry();
});

/**
 * 点击高薪职位跳转到职位详情页面
 */
const jobinfo = (jobId) => {
  router.push({ path: `/jobinfo/${jobId}` });
};

import { ElMessage } from "element-plus";
import store from "@/store";
import { computed } from "vue";
// jQuery 逻辑
import { reactive } from "vue";

/**
 * 轮播图
 */
//图片数组
let imgArr = ["1.jpg", "2.jpg", "3.gif"];
//图片索引
let carouselIndex = ref(1);
//默认展示的图片
let carouselImage = ref(
  require("../assets/images/" + imgArr[carouselIndex.value])
);
//切换图片
let changeCarousel = function () {
  if (carouselIndex.value < 2) {
    carouselIndex.value++;
  } else {
    carouselIndex.value = 0;
  }
  carouselImage.value = require("../assets/images/" +
    imgArr[carouselIndex.value]);
};
//定时器
let timer = setInterval(changeCarousel, 3000);
//组件卸载之前清除定时器
onBeforeUnmount(() => {
  clearInterval(timer);
});

/**
 * 个人中心
 */
//页面跳转
let personalIndex = function () {
  router.push({ name: "personal" });
};

/**
 * 我的职位
 */
//页面跳转
let personalSelect = function () {
  router.push({ name: "personalSelected" });
};

/**
 * 填写简历
 */
//页面跳转
let resumeWrite = function () {
  router.push({ name: "resume" });
};

/**
 * 登录模块
 */
const user = reactive({
  username: "",
  password: "",
});

//定义规则
const rules = reactive({
  username: [
    {
      required: true,
      message: "账号不能为空",
      trigger: "blur",
    },
    {
      min: 5,
      max: 20,
      message: "账号必须在5到20位",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "密码不能为空",
      trigger: "blur",
    },
    {
      min: 5,
      max: 15,
      message: "密码必须在5到15位 ",
      trigger: "blur",
    },
  ],
});

//发送登录请求
let isDisabled = ref(false); //按钮状态，是否禁用
const userLogin = function () {
  isDisabled.value = true;
  store
    .dispatch("LOGIN", user)
    .then(() => {
      //解除禁用
      isDisabled.value = false;
      router.push({ name: "Home" });
    })
    .catch((err) => {
      isDisabled.value = false;
      const errorMessage = err.data?.message || "登录失败，请重试";
      ElMessage.error(errorMessage);
    });
};

//判断登录状态
let loginStatus = computed(() => store.getters.isLogin);

//显示用户昵称
let nickname = computed(() => store.state.user.nickname);

/**
 * 用户退出
 */
let logout = function () {
  store
    .dispatch("LOGOUT")
    .then(() => {
      router.push({ name: "login" });
    })
    .catch((err) => {
      console.log(err);
      const errorMessage = err.data?.message || "退出失败，请重试";
      ElMessage.error(errorMessage);
    });
};

function search() {
  router.push("/searchJob");
}
</script>

<style scoped>
/* 引入外部样式 */
@import url("@/assets/css/style.css");

/* 自定义样式 */
.container {
  font-family: Arial, sans-serif;
}

/*新增 */
/*忘记密码 */
.forgot-password {
  text-decoration: none; /* 移除下划线 */
  color: #dc3545; /* 设置链接颜色 */
  margin-left: 10px; /* 增加左边距 */
}

.forgot-password:hover {
  text-decoration: underline; /* 添加悬停效果 */
}

/* 新增的样式 */
.user-info-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px; /* 设置宽度为正方形 */
  height: 100px; /* 设置高度为正方形 */
  background-color: #f8f9fa; /* 设置背景颜色 */
  border: 1px solid #ddd; /* 设置边框 */
  border-radius: 5px; /* 设置边框圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 设置阴影效果 */
}

.user-info-container p {
  margin: 5px 0; /* 设置段落上下边距 */
  font-size: 14px; /* 设置字体大小 */
  color: #333; /* 设置字体颜色 */
}

.user-info-container .lobtn {
  width: 80px; /* 设置按钮宽度 */
  height: 30px; /* 设置按钮高度 */
  font-size: 12px; /* 设置按钮字体大小 */
  background-color: #007bff; /* 设置按钮背景颜色 */
  border: none; /* 移除按钮边框 */
  color: white; /* 设置按钮字体颜色 */
  border-radius: 4px; /* 设置按钮圆角 */
  cursor: pointer; /* 设置鼠标悬停时变为手形 */
}

.user-info-container .lobtn:hover {
  background-color: #0056b3; /* 设置按钮悬停时的背景颜色 */
}

/*登录样式*/

.loginbbtn {
  text-align: center;
}

.welcome-message {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.welcome-message p {
  margin: 5px 0;
}

.slogan {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.greeting-blessing {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.greeting-blessing p {
  margin: 0;
}
</style>